package com.luo.listener;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.annotation.WebListener;
import java.io.File;
import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;

@WebListener
public class ServletContextListener implements javax.servlet.ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        ServletContext servletContext = sce.getServletContext();
    }

    @Override
    public void contextDestroyed(final ServletContextEvent sce) {
        System.out.println("服务器文件备份中......");
        // 获取当前服务器位置
        ServletContext servletContext = sce.getServletContext();
        String serverLocation = servletContext.getRealPath("/imgs");
        System.out.println("Server Location: " + serverLocation);

        String path = servletContext.getRealPath("/");
        // 创建File对象表示当前目录
        File currentDirFile = new File(path);
        // 获取当前目录的上一级目录
        String parentDirectory = currentDirFile.getParent();
        File grandparentDirFile = new File(parentDirectory);
        String grandparentDirectory = grandparentDirFile.getParent();

        // 指定源文件夹路径
        String sourceFolderPath = serverLocation;
        // 指定目标文件夹路径
        String targetFolderPath = grandparentDirectory + File.separator + "\\src\\main\\webapp\\imgs";
        // 调用复制方法
        try {
            copyFolder(sourceFolderPath, targetFolderPath);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void copyFolder(String sourceFolderPath, String targetFolderPath) throws IOException {
        Path sourcePath = Paths.get(sourceFolderPath);
        Path targetPath = Paths.get(targetFolderPath);

        // 使用Files.copy递归地复制文件夹
        Files.walkFileTree(sourcePath, EnumSet.noneOf(FileVisitOption.class), Integer.MAX_VALUE, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                Path targetDir = targetPath.resolve(sourcePath.relativize(dir));
                Files.createDirectories(targetDir);
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                Files.copy(file, targetPath.resolve(sourcePath.relativize(file)), StandardCopyOption.REPLACE_EXISTING);
                return FileVisitResult.CONTINUE;
            }
        });
    }
}
